import router from "./router"
import store from "./store"
import NProgress from "nprogress" // progress bar
import "nprogress/nprogress.css" // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from "@/utils/get-page-title"
// import permission from "@/store/modules/permission"

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ["/login"] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // const hasRoleCode = window.sessionStorage.getItem("roleCode") || ""
  // next()
  if (getToken()) {
    if (to.path === "/login") {
      next({ path: "/" })
      NProgress.done()
    } else {
      // 本项目登录接口和获取用户信息接口合二为一了，判断静态路由和总路由是否一致，一致调用接口
      if (store.getters.permission_routes.length == store.getters.routeLen) {
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          store.getters.roleCode
        )
        router.addRoutes(accessRoutes) // 动态添加可访问路由表
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
